<template>
  <div>
    <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible" fullscreen center>
      <el-button class="miui-dialog-close-btn" @click="visible = false">关闭页面</el-button>
      <el-divider content-position="left">单据信息</el-divider>
      <el-form :model="dataForm" ref="dataForm" label-width="90px">
        <el-row>
          <el-col :span="8" v-if="dataForm.id">
            <el-form-item label="单据编号" prop="takeBillId">
              <el-input v-model="dataForm.takeBillId" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单据日期" prop="createTime">
              <el-input v-model="dataForm.createTime" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="领用部门">
              <el-select v-model="dataForm.receptionId" placeholder="请选择">
                <el-option v-for="item in receptionDeptOptions" :value="item.id" :label="item.name" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8" v-if="dataForm.id==0">
            <el-form-item label="发出部门">
              <el-select v-model="dataForm.outDeptId" placeholder="请选择" @change="selectOutDeptId">
                <el-option v-for="item in receptionDeptOptions" :value="item.id" :label="item.name" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发出仓位">
              <el-select size="mini" v-model="dataForm.outStockId" @change="selectOutStockId">
                <el-option v-for="item in stockOptions" :value="item.id" :label="item.name" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="制单人" prop="createUserName">
              <el-input v-model="dataForm.createUserName" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="memo">
              <el-input v-model="dataForm.memo"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-radio-group v-model="calculate">
              <el-radio label="1">自动计算</el-radio>
              <el-radio label="2">手动计算</el-radio>
            </el-radio-group>
          </el-col>
          <el-form :inline="true">
            <el-form-item>
              <el-button type="primary" @click="addGoodsBySingle">单品添加商品</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="barcodeScan()">条码扫描</el-button>
            </el-form-item>
            <el-form-item style="float: right;">
              <el-button type="danger" @click="delTableData">删除</el-button>
            </el-form-item>
          </el-form>
        </el-row>
      </el-form>

      <el-divider content-position="left">商品信息</el-divider>

      <div class="avue-crud">
        <el-table :data="dataList" border v-loading="dataListLoading" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="40"></el-table-column>
          <el-table-column prop="goodsCode" label="商品代码" width="140"></el-table-column>
          <el-table-column prop="viewGoodsName" label="商品名称" min-width="230"></el-table-column>
          <el-table-column prop="spec" label="型号" width="80"></el-table-column>
          <el-table-column prop="unitType" label="计量单位" width="80"></el-table-column>
          <el-table-column prop="storageQuantity" label="可用库存数量" width="80"></el-table-column>
          <el-table-column prop="number" label="数量" width="60">
            <template slot-scope="scope">
              <el-input v-model="scope.row.number" @change="changeNumber"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="goodsBarcode" label="商品条码"></el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit" :loading="ischeck" v-prevent-re-click style="margin-right: 5px;">保存</el-button>
        <el-switch v-model="dataForm.isAudit" active-text="保存并审核" active-value="1" inactive-value="0"></el-switch>
      </span>

      <outbound-goods v-if="outboundVisible" ref="outboundAdd" @refreshForm="updateFormData"></outbound-goods>
      <!-- 弹窗，条码扫描  -->
      <barcode-scan v-if="barcodeVisible" ref="barcodeDialog" @refreshData="getBarcodeGoodsData"></barcode-scan>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getTakeInventoryInfo,
    addOtherOutbound,
    editRecipientsOfOutbound
  } from "@/api/eims/take-inventory/other-outbound"
  import { mapGetters } from "vuex"
  import {
    getStockList,
    getStockInfo
  } from "@/api/eims/stock"
  import { getDeptInfo } from "@/api/admin/dept"
  import {
    timeCompute,
    timeString
  } from "@/util/tools"
  import OutboundGoods from "./outbound-goods"
  import BarcodeScan from '@/components/business/BarcodeScan'

  export default {
    data() {
      return {
        ischeck: false,
        dataListLoading: false,
        visible: false,
        calculate: '1',
        dataForm: {
          id: 0,
          detailList: [],
          outDeptId: '',
          outStockId: "",
          receptionId: '',
          memo: "",
          isAudit: ""
        },
        receptionTypeOptions: [{
          label: "领用部门",
          value: 1
        }],
        receptionDeptOptions: [],
        stockOptions: [],
        dataList: [],
        outboundVisible: false,
        barcodeVisible: false
      };
    },
    created() {
      this.getDeptList();
    },
    computed: {
      ...mapGetters(["userInfo"])
    },
    components: {
      OutboundGoods,
      BarcodeScan
    },
    methods: {
      init(id) {
        this.dataForm.id = id || 0;
        this.visible = true;
        this.dataForm.isAudit = "0"
        this.dataForm.outDeptId = 1;
        this.dataForm.receptionId = '';
        this.dataForm.createTime = timeCompute(new Date());
        this.dataForm.createUserName = this.userInfo.realName;
        this.dataForm.detailList = [];
        this.calculate = '1'
        this.dataList = [];
        if (this.dataForm.id) {
          getStockList().then(response => {
            if(response.data.code == '0'){
              this.stockOptions = response.data.data
            }else{
              this.$message.error(response.data.msg)
            }
          })
        } else {
          getStockInfo(this.dataForm.outDeptId).then(response => {
            if(response.data.code == '0'){
              this.dataForm.outStockId = response.data.data[0].id
              this.stockOptions = response.data.data
            }else{
              this.$message.error(response.data.msg)
            }
          })
        }
        this.$nextTick(() => {
          this.$refs["dataForm"].resetFields();
          if (this.dataForm.id) {
            this.dataListLoading = true;
            getTakeInventoryInfo(this.dataForm.id).then(response => {
              if(response.data.code == '0'){
                this.dataForm = response.data.data
                this.dataList = response.data.data.detailList
              }else{
                this.$message.error(response.data.msg)
              }
              this.dataListLoading = false
            })
          }
        })
      },
      // 打开商品列表弹窗
      addGoodsBySingle() {
        if (this.dataForm.outStockId) {
          let params = {
            outStockId: this.dataForm.outStockId
          };
          let data = {
            paramsData: params,
            tableData: this.dataList
          };
          this.outboundVisible = true;
          this.$nextTick(() => {
            this.$refs.outboundAdd.init(data);
          });
        } else {
          this.$message.warning("请选择发出仓位");
        }
      },
      handleSelectionChange(val) {
        this.selectionList = val;
      },
      // 删除选中的商品
      delTableData() {
        let data = this.selectionList;
        data.forEach(item => {
          this.dataList.splice(item, 1);
        });
      },
      //更新表单数据
      updateFormData(data) {
        this.dataList = [];
        data.forEach(item => {
          this.dataList.push({
            goodsId: item.goodsId,
            goodsCode: item.code,
            viewGoodsName: item.name,
            spec: item.spec,
            number: 0,
            storageQuantity: item.storageQuantity,
            costPrice: item.notTaxPrice,
            taxPrice: item.taxPrice,
            costPriceTotal: 0,
            taxRate: item.taxRate,
            price: item.goodsPrice,
            priceTotal: 0,
            goodsBarcode: item.barcode,
          });
        });
      },
      //发出部门改变事件
      selectOutDeptId() {
        getStockInfo(this.dataForm.outDeptId).then(response => {
          if(response.data.code == '0'){
            if (response.data.data.length > 0) {
              this.dataForm.outStockId = response.data.data[0].id
            } else {
              this.dataForm.outStockId = ''
            }
            this.stockOptions = response.data.data
          }else{
            this.$message.error(response.data.msg)
          }
        })
        this.dataList = []
      },
      //领用部门改变事件
      selectOutStockId() {
        this.dataList = []
      },
      // 获取领用、发出部门列表
      getDeptList() {
        getDeptInfo().then(response => {
          if(response.data.code == '0'){
            this.receptionDeptOptions = response.data.data
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      //根据税率改变成本价格
      changeTaxRate() {
        if (this.calculate == 1) {
          this.dataList.forEach(item => {
            item.costPrice = item.taxPrice / (1 + item.taxRate / 100)
            item.costPriceTotal = item.number * item.costPrice;
            item.priceTotal = item.number * item.price;
          })
        }
      },
      //根据数量改变总价
      changeNumber() {
        if (this.calculate == 1) {
          this.dataList.forEach(item => {
            item.costPriceTotal = item.number * item.costPrice;
            item.priceTotal = item.number * item.price;
            item.costPrice = item.taxPrice / (1 + item.taxRate / 100)
          })
        }
      },
      //  条码扫描
      barcodeScan() {
        this.barcodeVisible = true
        this.$nextTick(() => {
          this.$refs.barcodeDialog.init(this.dataForm.outStockId)
        })
      },
      //  条码扫描获取的数据
      getBarcodeGoodsData(data) {
        let obj = {...data}
        obj.goodsId = obj.id
        let result = this.dataList.some(item => {
          return item.goodsBarcode == obj.goodsBarcode
        })

        if(result){
          this.dataList.forEach(item => {
            if(item.goodsBarcode == obj.goodsBarcode){
              item.allocationQuantity += 1
            }
          })
        }else{
          this.dataList.push(obj)
        }
      },
      //保存按钮
      dataFormSubmit() {
        if (!this.dataForm.receptionId) {
          this.$message.warning("请选择领用部门");
          return;
        }
        if (this.dataList.length <= 0) {
          this.$message.warning("请选择商品");
          return;
        }
        for (let i = 0; i < this.dataList.length; i++) {
          if (this.dataList[i].number <= 0 || Number(this.dataList[i].number) > Number(this.dataList[i].storageQuantity)) {
            this.$message.warning("请设置正确的商品数量,商品数量不能为0且不能大于库存量");
            return;
          }
        }
        this.dataForm.detailList = this.dataList;
        this.ischeck = true
        if (this.dataForm.id) {
          editRecipientsOfOutbound(this.dataForm).then(response => {
            if(response.data.code == '0'){
              this.$message.success('修改成功')
              this.visible = false
              this.$emit('refreshDataList')
            }else{
              this.$message.error(response.data.msg)
            }
            this.ischeck = false
          }).catch(() => {
            this.ischeck = false
          })
        } else {
          addOtherOutbound(this.dataForm).then(response => {
            if(response.data.code == '0'){
              this.$message.success("新增成功")
              this.visible = false
              this.$emit('refreshDataList')
            }else{
              this.$message.error(response.data.msg)
            }
            this.ischeck = false
          }).catch(() => {
            this.ischeck = false
          })
        }
      }
    }
  };
</script>
<style>
  .el-divider__text,
  .el-link {
    font-size: 18px;
  }
</style>
